<script setup>
import { ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { onLoad, onReady } from "@dcloudio/uni-app";
import { searchMessages, updateMsgStatus } from "@/global/chatApi";
import tabsMsg from "./message/tabsMsg.vue";
import imgMsg from "./message/imgMsg.vue";
import videoMsg from "./message/videoMsg.vue";
import useChat from "@/store/useChat.js";
import useAgent from "@/store/useAgent.js";
import { nextTick } from "process";
const useChatStore = useChat();
const useAgentStore = useAgent();
const { session, clientReplayText, userInputText, waitReplay } =
  storeToRefs(useChatStore);
const msgItem = ref("");
const headerTop = ref(null);
const getMoreFlag = ref(false);
let msgPages = 1;
onLoad(() => {
  // 监听键盘弹出事件
  uni.onKeyboardHeightChange((res) => {
    if (res.height > 0) {
      headerTop.value = res.height;
    } else {
      headerTop.value = 0;
    }
  });
  //获取聊天记录
  searchMessages({
    senderId: uni.getStorageSync("currentUserId"),
    receiverId: useAgentStore.agentId,
    limit: 100,
    groupId: useChatStore.currentSessionId,
  }).then((res) => {
    if (res.code === 200) {
      useChatStore.setMessage(res.data);
      onUpdateMsgStatus(res.data);
      nextTick(() => {
        msgItem.value = `bottom-msg-box`;
      });
    }
  });
});

//查找未读消息，将未读的回复更改为已读
const onUpdateMsgStatus = (msgArr) => {
  if (Array.isArray(msgArr) && msgArr.length) {
    let requestIds = [];
    let groupId = msgArr[0].groupId;
    msgArr.map((item) => {
      if (item.isRead == 0 && item.requestId && item.requestId != "null") {
        //如果是未读消息
        requestIds.push(item.requestId);
      }
    });

    if (requestIds.length) {
      let data = {
        groupId: groupId,
        requestIds: requestIds,
        QorA: "QA",
        updateStatus: 2,
      };
      updateMsgStatus(data).then(() => {
        console.log("已同步消息");
      });
    }
  }
};

//获取更多聊天记录
const getMoreMsg = () => {
  //后续需要接口返回总页码 根据页码判断处理逻辑
  // if (总页码)
  if (msgPages == 1) {
    msgPages += 1;
    return;
  }
  getMoreFlag.value = true;
  setTimeout(() => {
    uni.showToast({
      icon: "none",
      title: "暂无更多",
    });
    getMoreFlag.value = false;
  }, 2000);
};

//聊天记录更新后默认拉到最底部
watch(
  session,
  (newVal) => {
    nextTick(() => {
      if (newVal.messages.length == 0) return;
      let lastNode = newVal.messages[newVal.messages.length - 1];
      msgItem.value = `msgItem${lastNode.id || lastNode.date || item.tempId}`;
      console.log(msgItem.value);
    });
  },
  { deep: true }
);

//clientReplayText 和 userInputText 都存在pinia里，在wsStore里通过接收websocket消息变化
//有回复流式输出的文字时 拉到最下边
watch(clientReplayText, (newVal) => {
  //0的话 流式输出的文字在列表里会被挡住
  if (newVal.length == 0) return;
  nextTick(() => {
    msgItem.value = `item-clientReplayText${newVal.length}`;
  });
});
//监听流式输入的文字变化 拉到最下边
watch(
  userInputText,
  (newVal) => {
    //0的话 流式输出的文字在列表里会被挡住
    if (newVal.length == 0) {
      console.log("asr输入完毕");
      return;
    }
    nextTick(() => {
      msgItem.value = `item-userInputText${newVal.length}`;
    });
  },
  { deep: true }
);
</script>

<template>
  <!-- v-scroll-bottom="session.messages" -->
  <!-- :style="{ marginTop: headerTop + 80 + 'px' }" -->

  <scroll-view
    class="message"
    upper-threshold="0"
    @scrolltoupper="getMoreMsg"
    id="msgviewst"
    :scroll-top="100000"
    :scroll-into-view="msgItem"
    scroll-with-animation
    scroll-y="true"
  >
    <view class="message-ul">
      <!-- <view class="get-more-msg" v-show="getMoreFlag">
        <u-loading-icon :show="getMoreFlag"></u-loading-icon>
      </view> -->
      <view
        v-for="item in session.messages"
        :key="item.id"
        :id="`msgItem${item.id || item.date}`"
      >
        <view
          class="main"
          :class="{ self: item.roleType == 'HUMAN' }"
          v-if="item.messageType == '1'"
        >
          <view>
            <text class="text">{{ item.content }}</text>
          </view>
        </view>
      </view>
      <!-- 选项卡 -->
      <!-- <tabs-msg></tabs-msg> -->
      <!-- 图片类型 -->
      <!-- <imgMsg /> -->
      <!-- 视频类型 -->
      <!-- <videoMsg :videoId="'video-1'" /> -->
      <!-- <videoMsg :videoId="'video-2'" /> -->

      <!-- 智能体流式回复的文字 -->
      <!-- 智能体回复前的loading效果 -->
      <view
        style="margin-bottom: 0"
        :id="'item-clientReplayText' + clientReplayText.length"
      >
      </view>

      <!-- 用户流式输入的文字 -->
      <view
        class="main self"
        :id="'item-userInputText' + userInputText.length"
        v-show="userInputText != ''"
      >
        <view>
          <text class="text">{{ userInputText }} </text>
        </view>
      </view>
      <view v-show="waitReplay" style="margin-bottom: 0">
        <view class="main" style="margin-bottom: 0">
          <view class="text">
            <u-loading-icon :show="true"></u-loading-icon>
          </view>
        </view>
      </view>
      <!--默认底部view-->
      <view :id="msgItem" style="height: 2rpx; margin: 0"></view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped></style>
